//
//  PKPublishLiveController.swift
//  Panku
//
//  Created by mac on 2017/2/15.
//  Copyright © 2017年 Monster. All rights reserved.
//

import UIKit
import TextFieldEffects
import ReactiveCocoa
import ReactiveSwift
import Result

import MJExtension
import SVProgressHUD

import GPUImage

class PKPublishLiveController: PKBaseViewController {
    
    //MARK: - init
    init(viewModel:PKPublishLiveViewModel){
        super.init(nibName: nil, bundle: nil)
        
        self.viewModel = viewModel
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - properties
    //viewModel
    var viewModel:PKPublishLiveViewModel?
    
    //UI
    lazy var startLiveLabel = UILabel()
    lazy var liveTitleTextField = KaedeTextField(frame: CGRect.zero)
    lazy var startLiveButton = PKBaseButton.createButton()
    lazy var dismissButton = PKBaseButton.createButton()
    
    var cameraUtils = PKCameraUtils.sharedInstance
//    var liveUtils:PKLiveUtils = {
//        let liveUtilsFactory = PKLiveUtilsHelper.factory()
//        let liveUtils = liveUtilsFactory()
//        return liveUtils
//    }()

    //MARK: - life circle
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
   
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //开始预览界面
        cameraUtils.startCapture()
        
//        //默认无滤镜
//        cameraUtils.setDefaultFilter()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //结束预览
        cameraUtils.stopCapture()
    }
    
    //MARK: - UI
    override func setupRootView() {
        view.backgroundColor = UIColor.red
    }
    
    override func setupSubViews() {
        view.addSubview(cameraUtils.previewView!)
        view.addSubview(startLiveLabel)
        view.addSubview(liveTitleTextField)
        view.addSubview(startLiveButton)
        view.addSubview(dismissButton)

        
        startLiveLabel.text = "给直播写个标题吧"
        startLiveLabel.textColor = UIColor.white
        startLiveLabel.font = UIFont.PKFont(Size: 21)
        
        //pop键盘
        let tapGesture = UITapGestureRecognizer { (_) in
            self.liveTitleTextField.endEditing(true)
        }
        cameraUtils.previewView!.addGestureRecognizer(tapGesture)
        
        
        dismissButton.setImage(R.image.publish_live_dismiss(), for: .normal)
        dismissButton.addBlock(for: .touchUpInside) { (_) in
            self.dismiss(animated: true, completion: { 
                //finish callback
            })
        }
        
        liveTitleTextField.textAlignment = .center
        
        liveTitleTextField.textColor = UIColor(hexString: "FFFFFF")
        liveTitleTextField.font = UIFont.systemFont(ofSize: 20)

        startLiveButton.setTitle("开始直播", for: .normal)
        startLiveButton.addBlock(for: .touchUpInside) { (_) in
            
            let name = self.liveTitleTextField.text ?? ""
            let imageUrl = ""
            let userId = PKLoginServices.getUserId()
            let userName = "馆长"
            
            PKPublishServices.newLive(name: name, address: "", imageUrl: imageUrl, userId: userId, userName: userName).map({ (dict) -> PKNewLiveModel? in
                
                let dictionary = dict as! NSDictionary
                
                if dictionary["ok"] as! Bool == false{
                    SVProgressHUD.showError(withStatus: "直播失败 " + (dictionary["msg"] as! String))
                    return nil
                }
                
                let model = PKNewLiveModel.mj_object(withKeyValues: dict)
                return model!
            }).startWithResult({ (result) in
                
                //dismiss hud
                SVProgressHUD.dismiss()
                
                let model = result.value!
                
                if model == nil{
                    SVProgressHUD.showError(withStatus: "直播失败，请重试")
                    return
                }
                
                //开始直播
                print(model)
                
                let url = model!.pushUrl
                
                let liveFactory = PKLiveUtilsHelper.factory()
                let liveUtils = liveFactory()
                liveUtils.createLiveView(With: url)
                liveUtils.play()
                
                
            })

        }
        
        startLiveButton.titleLabel?.font = UIFont.PKFont(Size: 19)
        startLiveButton.setTitleColor(UIColor(hexString: "FFFEFF"), for: .normal)
        startLiveButton.backgroundColor = UIColor(hexString: "333333")
        startLiveButton.layer.masksToBounds = true
        startLiveButton.layer.cornerRadius = 3
        
    }
    
    override func setupSubViewsConstraints() {
        
        startLiveLabel.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.top).offset(160*D_FACTOR_Y)
            make.centerX.equalTo(view.snp.centerX)
        }
        
        cameraUtils.previewView?.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        dismissButton.snp.makeConstraints { (make) in
            make.top.equalTo(view.snp.top).offset(10)
            make.right.equalTo(view.snp.right).offset(-10)
            make.width.equalTo(44)
            make.height.equalTo(44)
        }
        
        liveTitleTextField.snp.makeConstraints { (make) in
            make.centerX.equalTo(view.snp.centerX)
            make.top.equalTo(view.snp.top).offset(236*D_FACTOR_Y)
            make.left.equalTo(view.snp.left).offset(12)
            make.right.equalTo(view.snp.right).offset(12)
            make.height.equalTo(50)
        }
        
        startLiveButton.snp.makeConstraints { (make) in
            make.top.equalTo(liveTitleTextField.snp.bottom).offset(60)
            make.left.equalTo(view.snp.left).offset(55)
            make.right.equalTo(view.snp.right).offset(-55)
            make.height.equalTo(40)
        }
        
    }
    
    override func setupNavigationBar() {
        
    }
    
    override func bindViewModel() {
        
    }
    
}
